<template>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" center :width="dialogWidth" @close="handleDialogCancel()"
        destroy-on-close>
        <div class="user_avatar">
            <p @click="avatarDialogVisible = true">更换头像</p>
            <img :src="state.form.avatar" alt="" @click="avatarDialogVisible = true" />
        </div>
        <el-form :model="state.form" label-width="120px" :inline="true" :rules="rules" ref="ruleFormRef">
            <el-form-item label="用户名" v-if="state.form.id == ''" prop="username">
                <el-input v-model="state.form.username" />
            </el-form-item>
            <el-form-item label="密码" v-if="state.form.id == ''" prop="password">
                <el-input type="password" v-model="state.form.password" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="state.form.nickname" />
            </el-form-item>
            <el-form-item label="手机" prop="phone">
                <el-input v-model="state.form.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="state.form.email" />
            </el-form-item>
            <el-form-item label="QQ" prop="qq">
                <el-input v-model="state.form.qq" />
            </el-form-item>
            <el-form-item label="微信" prop="wechat">
                <el-input v-model="state.form.wechat" />
            </el-form-item>
            <el-form-item label="状态" prop="active">
                <el-switch v-model="state.form.active" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="state.form.sex">
                    <el-radio :label="0">未知</el-radio>
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="角色" prop="roleIds">
                <el-select v-model="state.form.roleIds" placeholder="请选择角色" multiple collapse-tags
                    collapse-tags-tooltip>
                    <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleDialogCancel()">关闭</el-button>
                <el-button type="primary" @click="handleDialogConfirm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <Avatar v-model:avatarDialogVisible="avatarDialogVisible" @handleDialogConfirm="handleDialogAvatarConfirm"
        @handleDialogCancel="avatarHandleDialogCancel" :imgStyle="{ width: 300, height: 300 }"
        :zoomStyle="{ middleZoom: 0.5, miniZoom: 0.3 }" :imgUrl="state.form.avatar" v-if="avatarDialogVisible" />
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { list, remove, add, edit } from '@/api/user'
import { roleAll } from '@/api/role'
import { ElMessage, ElTable } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import Avatar from "@/components/avatar/Avatar.vue";
import { dialogAutoWidth } from '@/utils/dialog'

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    username: [{ required: true, message: "用户名不能为空", trigger: 'blur' }, { pattern: /^[a-zA-Z0-9_-]{1,16}$/, message: '请输入正确的用户名' }],
    password: [{ required: true, message: "密码不能为空", trigger: 'blur' }, { pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '密码长度必须4-16位数字和字母' }],
    active: [{ required: true, message: "状态不能为空", trigger: 'blur' }],
    sex: [{ required: true, message: "性别不能为空", trigger: 'blur' }],
    roleIds: [{ required: true, message: "角色不能为空", trigger: 'change' }],
    nickname: [{ required: true, message: "昵称不能为空", trigger: 'blur' }],
    email: [{ required: true, message: "邮箱不能为空", trigger: 'blur' }, { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '请输入正确的邮箱' }],
    phone: [{ required: true, message: "手机不能为空", trigger: 'blur' }, { pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的手机号' }],
    qq: [{ pattern: /^[1-9][0-9]{4,10}$/, message: '请输入正确的QQ号' }],
    wechat: [{ pattern: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/, message: '请输入正确的微信号' }],
})

let dialogWidth = ref("30%")
// 生命周期
onMounted(() => {
    getWindowResize()
    //获取角色列表
    getRoleAll(null);
})
// 获取屏幕尺寸
const getWindowResize = function () {
    dialogWidth.value = dialogAutoWidth;
}


let state = reactive<any>({
    form: {
        id: "",
        nickname: "",
        phone: "",
        email: "",
        sex: 0,
        active: true,
        username: "",
        password: "",
        qq: "",
        wechat: "",
        avatar: "",
        roleIds: [],
    },
})

// 传值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        required: true,
        default: false,
    },
    dialogTitle: {
        type: String,
        required: true,
        default: '',
    },
    dialogData: {
        type: Object,
        default: () => { },
    }
})
// 监听
watch(() => props.dialogData, () => {
    state.form = props.dialogData;
}, { deep: true, immediate: true })

// 获取角色列表
let roles = ref<any[]>([])
const getRoleAll = async (roleName: any) => {
    let res: any = await roleAll(roleName);
    if (res.code == '200') {
        roles.value = res.data;
    }
}

// 事件派发
const emits = defineEmits(["dialogClose", "getListData"])

// 弹框中的取消按钮事件
const handleDialogCancel = () => {
    emits("dialogClose", false)
};

// 弹出框确定按钮事件
const handleDialogConfirm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
        if (valid) {
            let res: any = {};
            if (state.form.id == "") {
                res = await add(state.form);
            } else {
                res = await edit(state.form);
            }
            if (res.code == "200") {
                ElMessage.success(res.message)
                emits('getListData')
                handleDialogCancel();
            }
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}


// 头像上传区域
// 控制 dialog 显示隐藏
let avatarDialogVisible = ref(false);
// 文本框
let base64Data = ref("");
interface ICropData {
    cropBase64: string;
    cropBlob: string;
}
const handleDialogAvatarConfirm = (param: ICropData) => {
    base64Data.value = param.cropBase64;
    avatarDialogVisible.value = false;
    state.form.avatar = base64Data.value;
};
const avatarHandleDialogCancel = () => {
    avatarDialogVisible.value = false;
}

</script>
<style lang="less" scoped>
.user_avatar {
    width: 100%;
    height: 160px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;

    & p {
        cursor: pointer;
        text-align: center;
        transition: all 0.6s;
        opacity: 0;
        width: 100%;
        color: red;
    }

    &:hover p {
        display: inline;
        opacity: 1;
        z-index: 1;
    }

    & img {
        cursor: pointer;
        width: 120px;
        height: 120px;
        border-radius: 90px;
        border: 5px solid #eeeeee;
        transition: all 0.6s;
    }

    &:hover img {
        filter: brightness(50%);
        opacity: 1;
    }
}

</style>